package com.example.domain.po;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@AllArgsConstructor
@Data
public class LoginUserDetails implements Serializable, UserDetails {

    private Users user;

    // 用户角色
    private List<String> roleNames;

    // 用户权限
    private List<String> permissionNames;

    //----------------实现UserDetails接口-----------------
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        //添加角色
        if(!CollectionUtils.isEmpty(roleNames)){
            //将角色设置到GrantedAuthority中，官网要求角色要加上前缀 ROLE_xxx 区分其它权限
            for (String roleName : roleNames) {
                if(StringUtils.hasText(roleName))
                authorities.add(new SimpleGrantedAuthority("ROLE_"+roleName));
            }
        }
        //添加权限
        if(!CollectionUtils.isEmpty(permissionNames)){
            //将权限设置到GrantedAuthority中
            for (String permissionName : permissionNames) {
                if(StringUtils.hasText(permissionName))
                authorities.add(new SimpleGrantedAuthority(permissionName));
            }
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
